//域名
import { baseUrl } from './baseUrl.js';

import { showTip } from './utils.js';

function http(opts) {
  let network;
  const token = opts.params && opts.params.token ? opts.params.token : uni.getStorageSync('token');
  const httpDefaultOpts = {
    url: opts.baseUrl ? opts.baseUrl + opts.url : baseUrl + opts.url,
    data: opts.params,
    method: opts.method,
    timeout: 20000,
    sslVerify: false,
    header: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': opts.method == 'GET' ? 'application/x-www-form-urlencoded' : 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    dataType: 'json',
  };

  if (token) {
    httpDefaultOpts.header.token = token;
  }

  return new Promise((resolve, reject) => {

    uni.getNetworkType({
      success: function (res) {
        network = res.networkType;
        if (res.networkType == 'none') {
          uni.showToast({
            title: '无网络',
            icon: 'none',
            duration: 5000
          });
        }
      }
    });

    //加载过程
    // uni.showLoading({
    //   title: '加载中',
    //   mask: true,
    // });

    uni.request(httpDefaultOpts).then(res => {
      if (res.statusCode == 200) {
        if (res.data.code == 401) {
          console.log('登录失效 token失效，请重新登录');
          expired();
        } else {
          resolve(res.data);
        }
      } else if (res.statusCode == 401) {
        expired();
      } else {
        showTip('服务器繁忙，请重试!');
        resolve(res.data);
      }
    }).catch(response => {
      reject(response);
    }).finally(() => {
      // uni.hideLoading();
    });
  });
}

//请求接口
const requestPort = (opts) => {
  opts.params = opts.params || {};
  return http(opts);
};

//图片上传
const imgUpload = (url, img) => {
  const token = uni.getStorageSync('token');
  if (!token) {
    uni.hideLoading();
    return false;
  }

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: baseUrl + url,
      filePath: img,
      name: 'file',
      header: {},
      formData: {
        'token': token
      },
      success: (uploadFileRes) => {
        resolve(JSON.parse(uploadFileRes.data));
      },
      fail: (err) => {
        reject(err);
      },
      complete() {
        uni.hideLoading();
      }
    });
  });
};


//图片上传
const httpUpload = (opts) => {
  let thisBaseUrl = baseUrl; //单独配置的域名
  let token = uni.getStorageSync('token');
  let formData = {};

  formData['token'] = token;
  let httpDefaultOpts = {
    url: thisBaseUrl + opts.url,
    filePath: opts.params,
    name: 'file',
    formData: formData
  }
  if (opts.formData && opts.formData.rLoading) {
    uni.showToast({
      title: '上传中',
      mask: true,
      icon: 'loading',
      duration: 5000
    });
  }
  let promise = new Promise(function (resolve, reject) {
    uni.uploadFile(httpDefaultOpts).then(
      (res) => {
        resolve(res.data);
        if (opts.formData && opts.formData.rLoading) {
          uni.hideToast();
        }
      }
    ).catch(
      (response) => {
        reject(response);
        if (opts.formData && opts.formData.rLoading) {
          uni.hideToast();
        }
      }
    )
  })
  return promise
};

//登录失效
function expired() {
  uni.removeStorageSync('token');
  uni.removeStorageSync('userInfo');
  uni.removeTabBarBadge({
    index: 3
  });
  uni.hideLoading();
  uni.navigateTo({
    url: '/pages/login/login'
  });
}

export {
  requestPort,
  imgUpload,
  httpUpload
};